package pe.com.jubre.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Autenticar extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String login;
	private String password;
	private Map<String, String> users;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		
		PrintWriter out = response.getWriter();
		
		this.login = request.getParameter("user");
		this.password = request.getParameter("pass");
		
		boolean flag = false;
		
		setUsers(this.users);
		
		if(this.users.containsKey(login)){
			flag = true;
		}
		
		String urlMenu = "menu.html";
		
		if(flag){
			if(this.users.get(login)!=null && this.users.get(login).equals(password)){
				HttpSession session = request.getSession();
				session.setAttribute("user", login);
				response.sendRedirect(urlMenu);
			}else{
				out.println("<script language='javascript'>");
                out.println("alert('El Password no es correcto intente de nuevo');");
                out.println("document.location.href='index.html';");
                out.println("</script>");
                out.close();
			}
		}else{
			out.println("<script language='javascript'>");
            out.println("alert('El Login especificado no existe intente de nuevo');");
            out.println("document.location.href='index.html';");
            out.println("</script>");
            out.close();
		}
	}

	public Map<String, String> getUsers() {
		return users;
	}

	public void setUsers(Map<String, String> users) {
		this.users = new HashMap<String, String>();
		this.users.put("maria", "123456");
		this.users.put("monica", "123456");
		this.users.put("yaqui", "123456");
	}
	
	
}
